package org.budo.solr.jdbc.driver.parser.jsqlparser;

import java.util.List;

import org.budo.jdbc.driver.exception.BudoJdbcDriverNotSupportedException;
import org.budo.jdbc.driver.parser.AbstractSqlStatementParser;
import org.budo.jdbc.driver.statement.JdbcStatement;
import org.budo.solr.jdbc.driver.statement.SelectStatement;

import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.FromItem;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.select.SelectBody;
import net.sf.jsqlparser.statement.select.SelectItem;

/**
 * @author lmw
 */
public class JsqlParserSolrStatementParser extends AbstractSqlStatementParser {
    @Override
    protected JdbcStatement doParseSql(String sql) throws Throwable {
        Statement statement = CCJSqlParserUtil.parse(sql);
        if (statement instanceof Select) {
            return this.parseSelect((Select) statement);
        }

        throw new BudoJdbcDriverNotSupportedException("#26 sql=" + sql);
    }

    private JdbcStatement parseSelect(Select select) {
        SelectBody selectBody = select.getSelectBody();
        if (selectBody instanceof PlainSelect) {
            return this.parsePlainSelect((PlainSelect) selectBody);
        }

        throw new BudoJdbcDriverNotSupportedException("#36 select=" + select);
    }

    private JdbcStatement parsePlainSelect(PlainSelect plainSelect) {
        List<SelectItem> selectItems = plainSelect.getSelectItems();
        for (SelectItem selectItem : selectItems) {
            System.err.println("selectItem=" + selectItem + ", " + selectItem.getClass());
        }

        FromItem fromItem = plainSelect.getFromItem();
        System.err.println("fromItem=" + fromItem + ", " + fromItem.getClass());

        SelectStatement selectStatement = new SelectStatement();
        return selectStatement;
    }
}